import numpy as np
import pandas as pd

def transform_to_local_coordinates(global_coords, mapaxes):
    """
    将大地坐标系中的点转换到局部坐标系。
    :param global_coords: 大地坐标系中的点 (x, y)
    :param mapaxes: MAPAXES 的三个点坐标 [Y轴点, 原点, X轴点]
    :return: 局部坐标系中的点 (x_local, y_local)
    """
    # 提取 MAPAXES 的三个点
    y_axis_point = np.array(mapaxes[0])
    origin = np.array(mapaxes[1])
    x_axis_point = np.array(mapaxes[2])

    # 计算局部坐标系的基向量
    x_axis_vector = x_axis_point - origin
    y_axis_vector = y_axis_point - origin

    # 归一化基向量
    x_axis_unit = x_axis_vector / np.linalg.norm(x_axis_vector)
    y_axis_unit = y_axis_vector / np.linalg.norm(y_axis_vector)

    # 将大地坐标转换为局部坐标
    global_coords = np.array(global_coords)
    local_coords = np.zeros_like(global_coords)

    for i in range(len(global_coords)):
        # 计算相对于原点的偏移
        offset = global_coords[i] - origin
        # 计算局部坐标
        local_coords[i, 0] = np.dot(offset, x_axis_unit)  # x_local
        local_coords[i, 1] = np.dot(offset, y_axis_unit)  # y_local

    return local_coords

def convert_fault_file(input_file, output_file, mapaxes):
    """
    转换 fault.txt 文件中的坐标到局部坐标系，并保存到 Excel 文件。
    :param input_file: 输入文件名 (fault.txt)
    :param output_file: 输出文件名 (Excel 文件)
    :param mapaxes: MAPAXES 的三个点坐标 [Y轴点, 原点, X轴点]
    """
    # 读取输入文件
    with open(input_file, 'r') as f:
        lines = f.readlines()

    # 解析数据
    data = []
    for line in lines:
        if line.strip():  # 跳过空行
            parts = line.split()
            if len(parts) == 4:
                x_global = float(parts[0])
                y_global = float(parts[1])
                column_id = int(parts[2])
                z = float(parts[3])
                data.append((x_global, y_global, column_id, z))

    # 提取大地坐标
    global_coords = [(x, y) for x, y, _, _ in data]

    # 转换到局部坐标系
    local_coords = transform_to_local_coordinates(global_coords, mapaxes)

    # 创建 DataFrame 保存结果
    df = pd.DataFrame({
        'X_local': local_coords[:, 0],
        'Y_local': local_coords[:, 1],
        'Column_ID': [d[2] for d in data],
        'Z': [d[3] for d in data]
    })

    # 保存为 Excel 文件
    df.to_excel(output_file, index=False)
    print(f"转换完成，结果已保存到 {output_file}")

# MAPAXES 的三个点坐标 [Y轴点, 原点, X轴点]
mapaxes = [
    (19643049.685, 3962356.1403),  # Y轴点
    (19643049.685, 3961356.1403),  # 原点
    (19644049.685, 3961356.1403)   # X轴点
]

# 输入文件和输出文件
#input_file = r'D:\360MoveData\Users\10758\Desktop\yuanzi\code\griddatatrans\决赛\data\GridA\faults.txt'
#output_file = r'D:\360MoveData\Users\10758\Desktop\yuanzi\code\griddatatrans\决赛\data\GridA\faults_local.xlsx'

input_file = r'D:\wins-desktop\pcl_geo1\raw_data\gridB\faults.txt'
output_file = r'D:\wins-desktop\pcl_geo1\raw_data\gridB\faults_local.xlsx'

# 执行转换
convert_fault_file(input_file, output_file, mapaxes)